from google.appengine.ext import db
import datetime

DEFAULT_DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'

class User(db.Model):
    name = db.StringProperty(required=True)
    email = db.EmailProperty()
    
class Event(db.Model):
    description = db.StringProperty(multiline=True)
    times = db.ListProperty(datetime.datetime)
    host = db.ReferenceProperty(User, required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    counts = db.ListProperty(long)
    updated = db.DateTimeProperty()
    
    def update_counts(self):
        last_updated = EventAttendee.gql('WHERE event = :1 ORDER BY updated DESC', self).get().updated
        if last_updated and (not self.updated or self.updated < last_updated):
            self.updated = last_updated
            self.counts = []
            for time in self.times:
                self.counts.append(EventAttendee.all().filter('event = ', self).filter('available = ', time).count())
            self.put()
        return self
    
    def get_attendees(self):
        return [{'name':attendee.user.name, 'available':attendee.available} for attendee in EventAttendee.all().filter('event = ', self).fetch(1000)]
    
    def get_status(self):
        return 'completed' if EventAttendee.gql('WHERE event = :1 AND updated != NULL', self).count() == EventAttendee.all().filter('event = ', self).count() else 'waiting'
    
    def as_map(self):
        return {
           'id':self.key().id(), 
           'host':self.host, 
           'description': self.description, 
           'created': self.created, 
           'updated': self.updated, 
           'times': self.times, 
           'counts': self.counts, 
           'attendees': self.get_attendees(), 
           'status': self.get_status()
        }
     
    def delete(self):
        attendees = EventAttendee.all().filter('event = ', self).fetch(1000)
        while len(attendees) > 0:
            [attendee.delete() for attendee in attendees]
            attendees = EventAttendee.all().filter('event = ', self).fetch(1000)
        super(Event, self).delete()
        
class EventAttendee(db.Model):
    event = db.ReferenceProperty(Event, required=True)
    user = db.ReferenceProperty(User, required=True)
    available = db.ListProperty(datetime.datetime)
    updated = db.DateTimeProperty()